import router from '@/router'
import { useCommonStore } from '@/stores/common'

/**
 * 分组分类排序
 * @param arr
 * @param label
 * @returns arr
 */
export function groudSort(arr: any[], label: string) {
  const map: any = {}
  const myArr = []
  for (let i = 0; i < arr.length; i++) {
    if (!map[arr[i][label]]) {
      myArr.push({
        [label]: arr[i][label],
        data: [arr[i]]
      })
      map[arr[i][label]] = arr[i]
    } else {
      for (let j = 0; j < myArr.length; j++) {
        if (arr[i][label] === myArr[j][label]) {
          myArr[j].data.push(arr[i])
          break
        }
      }
    }
  }
  return myArr
}
/**
 * 跳转页面
 * @param path
 * @param menuName 面包屑标题
 * @param parentName menu父级name 参考路由信息
 * @param isNoBread 不添加到面包屑
 * @description 当跳转页面在左侧菜单栏上时，需添加parentName，否则页面报错
 */
export const goPage = ({
  path,
  menuName,
  parentName,
  isNoBread
}: {
  path: string
  menuName?: string
  parentName?: string
  isNoBread?: boolean
}) => {
  if (!isNoBread) {
    useCommonStore().addBreadcrumbs({
      path,
      name: Math.random() + '',
      menuName: menuName || '',
      parentName: parentName || '',
      hidden: true
    })
  }
  router.push(path)
}
export const goBack = () => {
  router.go(-1)
}
// 权限功能校验
export const roleAuth = (value: string | string[]): boolean => {
  const currentPageRoles: string[] = JSON.parse(sessionStorage.getItem('userPermissions') as string)
  if (currentPageRoles[0] === '*:*:*') return true
  if (value instanceof Array && value.length) {
    const hasPermission = value.every((item) => currentPageRoles.includes(item))
    if (!hasPermission) return false
  } else {
    //@ts-ignore
    if (!currentPageRoles.includes(value)) return false
  }
  return true
}
